//
//  PhotoMovieViewController.m
//  06 美拍相机
//
//  Created by dllo on 16/3/17.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "PhotoMovieViewController.h"
#import "PhotoVideoViewController.h"

#import "PhotoCollectionViewCell.h"
#import "SelectedPhotoCollectionViewCell.h"

#import <AssetsLibrary/AssetsLibrary.h>

@interface PhotoMovieViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

// 获得相册
@property(nonatomic, strong)ALAssetsLibrary *library;

// 显示图片
@property (strong, nonatomic) IBOutlet UICollectionView *photoCollectionView;
// 保存图片
@property(nonatomic, strong)NSMutableArray *albumResultArr;

// 显示被选中的图片
@property (strong, nonatomic) IBOutlet UICollectionView *selectedPhotoCollectionView;
// 保存被选中的图片
@property(nonatomic, strong)NSMutableArray *selectedPhotoArr;

@end

@implementation PhotoMovieViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // 创建视图
    [self createView];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // 获得图片
    [self getPhoto];
}

#pragma mark 创建视图
- (void)createView{
    
    // 初始化数组
    self.selectedPhotoArr = [NSMutableArray array];
    
    self.photoCollectionView.showsVerticalScrollIndicator = NO;
    
    UINib *photoNib = [UINib nibWithNibName:NSStringFromClass([PhotoCollectionViewCell class]) bundle:nil];
    
    [self.photoCollectionView registerNib:photoNib forCellWithReuseIdentifier:NSStringFromClass([PhotoCollectionViewCell class])];
    
    UINib *selectedNib = [UINib nibWithNibName:NSStringFromClass([SelectedPhotoCollectionViewCell class]) bundle:nil];
    [self.selectedPhotoCollectionView registerNib:selectedNib forCellWithReuseIdentifier:NSStringFromClass([SelectedPhotoCollectionViewCell class])];
    
}

#pragma mark CollectionView的协议方法
// 个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if(collectionView == self.photoCollectionView){
        return self.albumResultArr.count;
    }
    else{
        return self.selectedPhotoArr.count;
    }
}
// 创建
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if(collectionView == self.photoCollectionView){
        PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([PhotoCollectionViewCell class]) forIndexPath:indexPath];
        
        ALAsset *result = self.albumResultArr[indexPath.row];
        CGImageRef ref = [result thumbnail];
        
        cell.imageView.image = [UIImage imageWithCGImage:ref];
        
        return cell;
    }
    else{
        SelectedPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SelectedPhotoCollectionViewCell class]) forIndexPath:indexPath];
        
        cell.showSelectedImageView.image = self.selectedPhotoArr[indexPath.row];
        
        
        cell.deleteButton.tag = 1000 + indexPath.row;
        [cell.deleteButton addTarget:self action:@selector(deleteSelectedPhoto:) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
    }
    
}

// 删除被选中的图片的触发方法
- (void)deleteSelectedPhoto:(UIButton *)button{
    NSInteger index = button.tag - 1000;
    
    [self.selectedPhotoArr removeObjectAtIndex:index];
    
    [self.selectedPhotoCollectionView reloadData];
}

// 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if(collectionView == self.photoCollectionView){
        if(self.selectedPhotoArr.count < 6){
            
            ALAsset *result = self.albumResultArr[indexPath.row];
            CGImageRef ref = [[result defaultRepresentation] fullResolutionImage];
            UIImage *img = [UIImage imageWithCGImage:ref];
            [self.selectedPhotoArr addObject:img];
            [self.selectedPhotoCollectionView reloadData];
            
            if(self.selectedPhotoArr.count >= 1){
                NSIndexPath *index = [NSIndexPath indexPathForItem:self.selectedPhotoArr.count - 1 inSection:0];
                [self.selectedPhotoCollectionView scrollToItemAtIndexPath:index atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
            }
        }
        else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"最多只能选择6张图片" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            // Action
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            // 添加
            [alert addAction:action];
            // 显示
            [self presentViewController:alert animated:YES completion:^{
            }];
        }
    }
}


// 获得图片的触发方法
- (void)getPhoto{
    
    self.library = [[ALAssetsLibrary alloc] init];
    
    self.albumResultArr = [NSMutableArray array];
    
    [self.library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

        // 设置相册的筛选条件,现在选择的是只包含图片
        [group setAssetsFilter:[ALAssetsFilter allPhotos]];
        
        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            
            if(result != nil){
                [self.albumResultArr addObject:result];
            }
        }];
        [self.photoCollectionView reloadData];
    } failureBlock:^(NSError *error) {
        
        
    }];
}

#pragma mark 将图片合成为视频的触发方法
- (IBAction)composeVideo:(id)sender {
    if(self.selectedPhotoArr.count < 3){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"最少需选择3张图片哦" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        // Action
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        // 添加
        [alert addAction:action];
        // 显示
        [self presentViewController:alert animated:YES completion:^{
        }];
    }
    else{
        // 跳转到合成视频的页面
        PhotoVideoViewController *photoVideoVC = [[PhotoVideoViewController alloc] initWithNibName:NSStringFromClass([PhotoVideoViewController class]) bundle:nil];
        photoVideoVC.imageArr = self.selectedPhotoArr;
        [self presentViewController:photoVideoVC animated:NO completion:^{
        }];
    }
}
// 返回上一页面
- (IBAction)backPreviousView:(id)sender {
    [self dismissViewControllerAnimated:NO completion:^{
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
